import { ComUtils } from "@/utils/Com"
import { createSignal, onCleanup, onMount } from "solid-js"
import 'grapesjs/dist/css/grapes.min.css';
import grapesjs, { Editor } from 'grapesjs';
import zh from 'grapesjs/locale/zh';
import '@/assets/css/template.css'
import { ButtonComp, CanvasComp, ColComp, ContainerComp, extendedStyleManager, ImageComp, InputComp, LinkComp, OptionComp, RowComp, SelectComp, TextAreaComp } from "./CustomTempComp";
import { TPL_LANGS } from "../config/tpl-lang";

interface Props {
    content: () => string
    close?: () => void
    save?: (code: string) => void
}
let editor: Editor
export default function (props: Props) {
    let box: any
    let blcok: any
    let style: any
    let trait: any
    let classes: any
    let layers: any
    const [contrTabIndex, setContrTabIndex] = createSignal(0)
    const getHtmlICon = (k: string) => {
        const url = ComUtils.getResourceUrl(`/icons/html/${k}.svg`)
        return `<img src="${url}" alt="${k}" />`
    }

    const initEditor = () => {
        if (!box) {
            return
        }
        let locale = 'en'
        if (chrome.i18n) {
            const lang = chrome.i18n.getUILanguage()
            if (lang === 'zh_CN' || lang === 'zh_TW') {
                locale = 'zh'
            }
        }
        const rect = box.getBoundingClientRect()
        editor = grapesjs.init({
            container: box,
            fromElement: true,
            storageManager: false,
            height: rect.height,
            width: rect.width,
            panels: { defaults: [] },
            avoidInlineStyle: false,
            i18n: {
                locale,
                messages: {
                    zh,
                }
            },
            plugins: [
                ContainerComp,
                RowComp,
                ColComp,
                CanvasComp,
                LinkComp,
                SelectComp,
                InputComp,
                ButtonComp,
                ImageComp,
                TextAreaComp,
                OptionComp,
            ],
            blockManager: {
                appendTo: blcok,
                blocks: [
                    {
                        id: 'container',
                        label: getHtmlICon('div'),
                        category: '',
                        content: { type: 'container' },
                    },
                    {
                        id: 'text',
                        label: getHtmlICon('span'),
                        content: '<span>This is a simple text</span>',
                    },
                    {
                        id: 'image',
                        label: getHtmlICon('img'),
                        select: true,
                        content: { type: 'myImage' },
                        activate: true,
                    },
                    {
                        id: 'canvas',
                        label: getHtmlICon('canvas'),
                        content: { type: 'canvas' },
                    },
                    {
                        id: 'video',
                        label: getHtmlICon('video'),
                        content: { type: 'video' },
                    },
                    {
                        id: 'link',
                        label: getHtmlICon('link'),
                        content: { type: 'link', attributes: { target: '_blank' } },
                    },
                    {
                        id: 'row',
                        label: getHtmlICon('row'),
                        content: { type: 'row' },
                    },
                    {
                        id: 'col',
                        label: getHtmlICon('col'),
                        content: { type: 'col' },
                    },
                    {
                        id: 'select',
                        label: getHtmlICon('select'),
                        content: { type: 'select' },
                    },
                    {
                        id: 'button',
                        label: getHtmlICon('button'),
                        content: { type: 'button' },
                    },
                    {
                        id: 'h1',
                        label: getHtmlICon('h1'),
                        content: '<h1>title-1</h1>',
                    },
                    {
                        id: 'input',
                        label: getHtmlICon('input'),
                        content: { type: 'input' },
                    },
                    {
                        id: 'textarea',
                        label: getHtmlICon('textarea'),
                        content: { type: 'textarea' },
                    },
                    {
                        id: 'option',
                        label: getHtmlICon('option'),
                        content: { type: 'option' },
                    },
                ]
            },
            styleManager: {
                appendTo: style,
            },
            traitManager: {
                appendTo: trait,
            },
            selectorManager: {
                appendTo: classes
            },
            layerManager: {
                appendTo: layers,
            },
            assetManager: {
                assets: [
                    ComUtils.getResourceUrl('/logo.png'),
                    ComUtils.getResourceUrl('/icons/save.svg'),
                    ComUtils.getResourceUrl('/icons/blockly_36.png'),
                    ComUtils.getResourceUrl('/icons/close.svg'),
                    ComUtils.getResourceUrl('/icons/delete.svg'),
                    ComUtils.getResourceUrl('/icons/edit.svg'),
                    ComUtils.getResourceUrl('/icons/html.svg'),
                    ComUtils.getResourceUrl('/icons/ic-download.svg'),
                    ComUtils.getResourceUrl('/icons/import.svg'),
                    ComUtils.getResourceUrl('/icons/new.svg'),
                    ComUtils.getResourceUrl('/icons/obj.svg'),
                    ComUtils.getResourceUrl('/icons/left.svg'),
                    ComUtils.getResourceUrl('/icons/right.svg'),
                    ComUtils.getResourceUrl('/icons/html/audio.svg'),
                    ComUtils.getResourceUrl('/icons/html/button.svg'),
                    ComUtils.getResourceUrl('/icons/html/canvas.svg'),
                    ComUtils.getResourceUrl('/icons/html/col.svg'),
                    ComUtils.getResourceUrl('/icons/html/div.svg'),
                    ComUtils.getResourceUrl('/icons/html/h1.svg'),
                    ComUtils.getResourceUrl('/icons/html/img.svg'),
                    ComUtils.getResourceUrl('/icons/html/input.svg'),
                    ComUtils.getResourceUrl('/icons/html/link.svg'),
                    ComUtils.getResourceUrl('/icons/html/row.svg'),
                    ComUtils.getResourceUrl('/icons/html/span.svg'),
                    ComUtils.getResourceUrl('/icons/html/select.svg'),
                    ComUtils.getResourceUrl('/icons/html/video.svg'),
                ]
            }
        })

        editor.I18n.addMessages(TPL_LANGS)

        extendedStyleManager(editor)
    }

    const saveCode = () => {
        const html = editor.getHtml().replace(/<\/?body>/gi, '').replace(/<style>[\s\S]*?<\/style>/gi, '')
        const style = editor.getCss()
        console.log(html)
        const code = `<style>${style}</style>${html}`
        props.save?.(code)
        props.close?.()
    }

    onMount(() => {
        initEditor()
    })

    onCleanup(() => {
        editor.destroy()
    })

    return <div class="fixed top-0 left-0 w-full h-full z-50 bg-[rgba(0,0,0,0.4)] p-8">
        <div class="bg-[#303030] border border-[#5e5e5e] rounded-lg w-full h-full flex gap-1 pb-[3rem]">
            <div ref={blcok} class="w-[10%] h-full overflow-y-auto">

            </div>
            <div ref={box} class="w-[70%] h-full overflow-y-auto" innerHTML={props.content()}>
            </div>
            <div class="w-[20%] h-full overflow-y-auto">
                <div class="flex items-center gap-2">
                    <button class=" cursor-default" classList={{ 'disabled': contrTabIndex() !== 0 }} onclick={() => setContrTabIndex(0)}>
                        {ComUtils.tr('style')}
                    </button>
                    <button class=" cursor-default" classList={{ 'disabled': contrTabIndex() !== 1 }} onclick={() => setContrTabIndex(1)}>
                        {ComUtils.tr('trait')}
                    </button>
                    <button class=" cursor-default" classList={{ 'disabled': contrTabIndex() !== 2 }} onclick={() => setContrTabIndex(2)}>
                        {ComUtils.tr('selector')}
                    </button>
                    <button class=" cursor-default" classList={{ 'disabled': contrTabIndex() !== 3 }} onclick={() => setContrTabIndex(3)}>
                        {ComUtils.tr('layer')}
                    </button>
                </div>
                <div ref={style} class="w-full" style={{ 'display': contrTabIndex() === 0 ? 'block' : 'none' }}></div>
                <div ref={trait} class="w-full" style={{ 'display': contrTabIndex() === 1 ? 'block' : 'none' }}></div>
                <div ref={classes} class="w-full" style={{ 'display': contrTabIndex() === 2 ? 'block' : 'none' }}></div>
                <div ref={layers} class="w-full" style={{ 'display': contrTabIndex() === 3 ? 'block' : 'none' }}></div>
            </div>
        </div>
        <div class="absolute z-50 bottom-4 w-full left-0 flex items-center justify-center gap-8 mt-6 py-4">
            <button class="btn" onclick={props.close}>
                {ComUtils.tr('cancel')}
            </button>
            <button class="btn" onclick={saveCode}>
                {ComUtils.tr('save')}
            </button>
        </div>
    </div>
}